<?php
namespace tp5_lib\cron\logic;

use tp5_lib\install\logic\Module;
use tp5_lib\install\logic\DynamicConfig;

class CronModule extends Module
{
    public function status()
    {
        try{
            $log = DynamicConfig::alloc("record")->read($this->name."-".time());
        }
        catch(\Exception $exce){
            return "available";
        }
        //最后运行时间三分钟以内，则认定任务计划/cron运行正常
        if($log["last_run_time"] + 180 < time()){
            return "available";
        }
        return "installed";
    }
    public function install()
    {
        if((!$log=$this->read("cron_log")) || ($log["last_run_time"] + 180 < time())){
            $this->error="请手动添加任务计划/crontab";
            return false;
        }
        $this->update();
        return true;
    }
    public function uninstall()
    {
        $this->error="请手动删除任务计划/crontab";
        return false;
    }
    public function update()
    {
        $tasks=[];
        $this->scan("cron",function($module, $config) use(&$tasks){
            foreach($config as &$task){
                $task["id"] = md5(json_encode($task));
            }
            $tasks=array_merge($tasks,$config);
        });
        $this->write("cron_task",$tasks);
        return true;
    }
}
